const jwt = require("jsonwebtoken");
const { JWT_SECRET } = require("../config/config.default");
const { tokenExpiredError, jsonWebTokenError, hadNoAdminPermission } = require("../constant/err.type");

//token验证
const authenticate = async (ctx, next) => {
  const { authorization } = ctx.request.header;
  const token = authorization.replace("Bearer ", "");
  //   console.log(token); //打印token信息

  try {
    //user中包含了payload的信息（id，user_name，is_admin,password）
    const user = jwt.verify(token, JWT_SECRET);
    ctx.state.user = user; //挂载user信息
  } catch (error) {
    switch (error.name) {
      case "TokenExpiredError":
        return ctx.app.emit("error", tokenExpiredError, ctx); //token过期
      case "JsonWebTokenError":
        return ctx.app.emit("error", jsonWebTokenError, ctx); //无效的token
      default:
        break;
    }
  }

  await next();
};

// 判断用户是否有admin权限
const hadAdminPermission = async (ctx, next) => {
  const { is_admin } = ctx.state.user;
  if (!is_admin) {
    // 没有管理员权限
    return ctx.app.emit("error", hadNoAdminPermission, ctx);
  }
  await next();
};
module.exports = {
  authenticate,
  hadAdminPermission,
};
